<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>考勤管理</title>
    <link rel="stylesheet" href="static/elementui.css">
    <script src="static/vue@2.6.14.js"></script>
    <script src="static/elementui.js"></script>
    <script src="static/axios.min.js"></script>
    <style>
        body {
            padding: 20px;
        }

        .toolbar {
            margin-bottom: 20px;
        }

        .dialog-footer {
            text-align: right;
        }

        .status-emoji {
            margin-right: 10px;
            font-size: 20px;
        }

        .no-students-hint {
            text-align: center;
            padding: 20px;
            color: #999;
        }
    </style>
</head>
<body>
<div id="app">
    <el-card>
        <div class="toolbar">
            <el-input placeholder="考勤搜索" v-model="searchKeyword" style="width: 200px;"></el-input>
            <el-button v-if="user.roleType === 'teacher'" type="primary" @click="handleAddAttendance" size="small">
                添加考勤
            </el-button>
        </div>
        <el-table :data="attendances" stripe>
            <el-table-column prop="courseName" label="课程名称"></el-table-column>
            <el-table-column prop="teacherName" label="教师名称"></el-table-column>
            <el-table-column prop="startTime" label="考勤开始时间"></el-table-column>
            <el-table-column prop="endTime" label="考勤结束时间"></el-table-column>
            <el-table-column prop="status" label="考勤状态"></el-table-column>
            <el-table-column v-if="user.roleType === 'teacher'" fixed="right" label="操作" width="180">
                <template slot-scope="scope">
                    <el-button @click="handleEdit(scope.row)" type="primary" size="small">编辑</el-button>
                    <el-button @click="handleDelete(scope.row)" type="danger" size="small">删除</el-button>
                    <el-button @click="handleViewAttendanceStatus(scope.row)" type="info" size="small">查看出勤数据
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="block">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 20, 50]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalAttendances">
            </el-pagination>
        </div>
    </el-card>

    <el-dialog :title="isEditMode ? '编辑考勤信息' : '添加考勤信息'" :visible.sync="dialogVisible">
        <el-form :model="currentAttendance" :rules="rules" ref="attendanceForm" label-width="100px">
            <el-form-item label="课程名称" prop="courseId">
                <el-select v-model="currentAttendance.courseId" placeholder="请选择课程">
                    <el-option v-for="course in courses" :key="course.id" :label="course.courseName"
                               :value="course.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="考勤开始时间" prop="startTime">
                <el-date-picker
                        v-model="currentAttendance.startTime"
                        type="datetime"
                        placeholder="选择考勤开始时间"
                        :picker-options="pickerOptionsStart">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="考勤结束时间" prop="endTime">
                <el-date-picker
                        v-model="currentAttendance.endTime"
                        type="datetime"
                        placeholder="选择考勤结束时间"
                        :picker-options="pickerOptionsEnd">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="考勤状态" prop="status">
                <el-select v-model="currentAttendance.status" placeholder="请选择考勤状态">
                    <el-option label="发布" value="发布"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false" size="small">取消</el-button>
            <el-button type="primary" @click="handleSave" size="small">保存</el-button>
        </div>
    </el-dialog>

    <el-dialog title="出勤数据" :visible.sync="attendanceStatusDialogVisible" width="80%">
        <el-collapse>
            <el-collapse-item
                    v-for="(status, index) in attendanceStatus"
                    :key="index"
                    :title="formatStatusTitle(status.status)"
                    :name="status.status"
            >
                <el-table
                        :data="status.students"
                        stripe
                        v-if="status.students.length > 0"
                >
                    <el-table-column prop="student_id" label="学生ID"></el-table-column>
                    <el-table-column prop="student_name" label="学生姓名"></el-table-column>
                    <el-table-column label="操作" width="120">
                        <template slot-scope="scope">
                            <el-button
                                    v-if="status.status == '补签申请'"
                                    type="primary"
                                    size="small"
                                    @click="handleReschedule(scope.row)">
                                补签
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div v-else class="no-students-hint">
                    {{ status.status === '未签到' ? '' : '🏫 暂无学生' }}
                </div>
            </el-collapse-item>
        </el-collapse>
        <div slot="footer" class="dialog-footer">
            <el-button @click="attendanceStatusDialogVisible = false" size="small">关闭</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                searchKeyword: '',
                attendances: [],
                totalAttendances: 0,
                pageSize: 5,
                currentPage: 1,
                dialogVisible: false,
                currentAttendance: {},
                isEditMode: false,
                user: {},
                courses: [],
                rules: {
                    courseId: [
                        {required: true, message: '请选择课程', trigger: 'blur'}
                    ],
                    startTime: [
                        {required: true, message: '请选择考勤开始时间', trigger: 'blur'},
                        {validator: this.validateStartTime, trigger: 'blur'}
                    ],
                    endTime: [
                        {required: true, message: '请选择考勤结束时间', trigger: 'blur'},
                        {validator: this.validateEndTime, trigger: 'blur'}
                    ],
                    status: [
                        {required: true, message: '请选择考勤状态', trigger: 'blur'}
                    ]
                },
                pickerOptionsStart: {
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7;
                    }
                },
                pickerOptionsEnd: {
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7;
                    }
                },
                attendanceStatusDialogVisible: false,
                attendanceStatus: []
            };
        },
        watch: {
            searchKeyword(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.currentPage = 1;
                    this.fetchAttendances();
                }
            },
            currentPage(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.fetchAttendances();
                }
            },
            pageSize(newVal, oldVal) {
                if (newVal !== oldVal) {
                    this.fetchAttendances();
                }
            }
        },
        methods: {
            fetchAttendances() {
                const teacherId = this.user.roleType === 'teacher' ? this.user.id : null;
                axios.get('/attendance', {
                    params: {
                        operation: 'findAttendancesByPageAndName',
                        teacherId: teacherId,
                        keyword: this.searchKeyword,
                        pageNum: this.currentPage,
                        pageSize: this.pageSize
                    }
                }).then(response => {
                    const {code, data} = response.data;
                    if (code === 200) {
                        this.attendances = data.list;
                        this.totalAttendances = data.total;
                    } else {
                        this.$message.error('获取考勤列表失败');
                    }
                }).catch(error => {
                    console.error('获取考勤列表失败:', error);
                    this.$message.error('获取考勤列表失败');
                });
            },
            handleAddAttendance() {
                this.isEditMode = false;
                this.currentAttendance = {
                    teacherId: this.user.id
                };
                this.fetchCourses();
                this.dialogVisible = true;
            },
            handleEdit(attendance) {
                this.isEditMode = true;
                this.currentAttendance = Object.assign({}, attendance);
                this.fetchCourses();
                this.dialogVisible = true;
            },
            handleSave() {
                this.$refs.attendanceForm.validate(valid => {
                    if (valid) {
                        const url = this.isEditMode ? '/attendance?operation=updateAttendance' : '/attendance?operation=insertAttendance';
                        axios.post(url, this.currentAttendance)
                            .then(response => {
                                if (response.data.code === 200) {
                                    this.$message.success(this.isEditMode ? '考勤信息更新成功' : '考勤添加成功');
                                    this.fetchAttendances();
                                } else {
                                    this.$message.error(this.isEditMode ? '考勤信息更新失败' : '考勤添加失败');
                                }
                            })
                            .catch(error => {
                                console.error(this.isEditMode ? '考勤信息更新失败:' : '考勤添加失败:', error);
                                this.$message.error(this.isEditMode ? '考勤信息更新失败' : '考勤添加失败');
                            });
                        this.dialogVisible = false;
                    }
                });
            },
            handleDelete(attendance) {
                this.$confirm('此操作将永久删除该考勤, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post('/attendance?operation=deleteAttendance&id=' + attendance.id)
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('考勤删除成功');
                                this.fetchAttendances();
                            } else {
                                this.$message.error('考勤删除失败');
                            }
                        })
                        .catch(error => {
                            console.error('考勤删除失败:', error);
                            this.$message.error('考勤删除失败');
                        });
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            },
            handleSizeChange(val) {
                this.pageSize = val;
            },
            handleCurrentChange(val) {
                this.currentPage = val;
            },
            fetchCourses() {
                axios.get('/course', {
                    params: {
                        operation: 'getAllCoursesByTeacherId',
                        teacherId: this.user.id
                    }
                }).then(response => {
                    const {code, data} = response.data;
                    if (code === 200) {
                        this.courses = data;
                    } else {
                        this.$message.error('查询教师所有课程失败');
                    }
                }).catch(error => {
                    console.error('查询教师所有课程失败:', error);
                    this.$message.error('查询教师所有课程失败');
                });
            },
            validateStartTime(rule, value, callback) {
                if (!value) {
                    callback(new Error('请选择考勤开始时间'));
                } else {
                    const currentTime = new Date();
                    if (new Date(value) < currentTime) {
                        callback(new Error('考勤开始时间必须大于等于当前时间'));
                    } else {
                        callback();
                    }
                }
            },
            validateEndTime(rule, value, callback) {
                if (!value) {
                    callback(new Error('请选择考勤结束时间'));
                } else {
                    if (new Date(value) <= new Date(this.currentAttendance.startTime)) {
                        callback(new Error('考勤结束时间必须大于考勤开始时间'));
                    } else {
                        callback();
                    }
                }
            },
            handleViewAttendanceStatus(attendance) {
                axios.get('/attendance', {
                    params: {
                        operation: 'getAttendanceStatusRatio',
                        attendanceId: attendance.id
                    }
                }).then(response => {
                    const {code, data} = response.data;
                    if (code === 200) {
                        const statusOrder = ['未签到', '已签到', '请假', '签到过期', '补签申请'];
                        this.attendanceStatus = statusOrder
                            .filter(status => data.statusStudentsMap[status])
                            .map(status => ({
                                status: status,
                                students: data.statusStudentsMap[status] || []
                            }));
                        this.attendanceStatusDialogVisible = true;
                    } else {
                        this.$message.error('查看出勤数据失败');
                    }
                }).catch(error => {
                    console.error('查看出勤数据失败:', error);
                    this.$message.error('查看出勤数据失败');
                });
            },
            formatStatusTitle(status) {
                const statusEmojis = {
                    '未签到': '📵 未签到',
                    '已签到': '✅ 已签到',
                    '请假': '🏥 请假',
                    '签到过期': '⏰ 签到过期',
                    '补签申请': '❓ 补签申请'
                };
                return `${statusEmojis[status]} (${this.attendanceStatus.find(s => s.status === status).students.length}人)`;
            },
            handleReschedule(student) {
                const updateData = {
                    id: student.id,
                    status: '已签到',
                    checkInTime: new Date().toISOString(),
                    studentId: student.student_id,
                };
                this.updateAttendanceRecord(updateData);
            },
            updateAttendanceRecord(updateData) {
                axios.post('/attendanceRecord?operation=update', updateData)
                    .then(response => {
                        const {code, msg} = response.data;
                        if (code === 200) {
                            this.$message.success(msg || '更新考勤记录成功 ✅');
                            this.fetchAttendances(); // 重新获取数据
                            this.attendanceStatusDialogVisible = false; // 关闭对话框
                        } else {
                            this.$message.error(msg || '更新考勤记录失败 🚫');
                        }
                    }).catch(error => {
                    console.error('更新考勤记录失败:', error);
                    this.$message.error('更新考勤记录失败 🚫');
                });
            }
        },
        mounted() {
            const userData = localStorage.getItem('user');
            if (userData) {
                this.user = JSON.parse(userData);
            }
            this.fetchAttendances();
        }
    });
</script>
</body>
</html>